const os = require("os");
const findPort = require("./findPort");
const { workspace } = require("vscode");
const proxy = require("./proxy");
const prepareProxy = require("./prepareProxy");

let server;

const startProxy = (resolve, proxyrc) =>
  findPort().then((port) => {
    proxyrc.port = port;
    if (proxyrc.proxy) {
      proxyrc.proxy = prepareProxy(proxyrc.proxy, "public");
    }
    server = proxy(proxyrc);
    return resolve({ server, port });
  });

module.exports = {
  start: function start() {
    return new Promise((resolve) => {
      workspace.findFiles("**/.proxyrc.js").then(async (files) => {
        if (files && files.length) {
          let filePath = files[0].path;
          if (os.type() === "Windows_NT") {
            filePath = filePath.substr(1);
          }
          delete require.cache[require.resolve(filePath)];
          let proxyrc = require(filePath);
          return startProxy(resolve, proxyrc);
        }
        return startProxy(resolve, {});
      });
    });
  },
  stop: function stop() {
    return new Promise((resolve) => {
      server && server.kill();
      return resolve();
    });
  }
};
